package com.btl.cygf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.btl.zujian.SelectPicPopup;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.yzx.yunyanzhengdemo.activity.LoginActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class JiaoHuanActivity extends Activity implements OnClickListener {
	ImageView login_backtofragment;
	TextView jiaohuanfabu;
	ImageView chuantu;
	TextView chuantu_id;
	private TextView LocationResult;
	EditText jiaohuanbiaotitext;
	EditText jianjietext;
	ImageView dingwei;
	LocationClient mLocationClient;
	private LocationMode tempMode = LocationMode.Hight_Accuracy;
	private String tempcoor = "gcj02";
	private CheckBox checkGeoLocation;
	private SelectPicPopup spp;

	private File file;
	private String filename;
	boolean flag = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.jiaohuan);

		mLocationClient = ((LocationApplication) getApplication()).mLocationClient;
		LocationResult = (TextView) findViewById(R.id.textView1);
		((LocationApplication) getApplication()).mLocationResult = LocationResult;

		login_backtofragment = (ImageView) findViewById(R.id.login_backtofragment);
		jiaohuanfabu = (TextView) findViewById(R.id.jiaohuanfabu);
		chuantu = (ImageView) findViewById(R.id.chuantu);
		chuantu_id = (TextView) findViewById(R.id.chuantu_id);

		jiaohuanbiaotitext = (EditText) findViewById(R.id.jiaohuanbiaotitext);
		jianjietext = (EditText) findViewById(R.id.jianjietext);
		dingwei = (ImageView) findViewById(R.id.dingwei);
		login_backtofragment.setOnClickListener(this);
		jiaohuanfabu.setOnClickListener(this);
		chuantu.setOnClickListener(this);
		dingwei.setOnClickListener(this);

		checkGeoLocation = (CheckBox) findViewById(R.id.geolocation);
		checkGeoLocation.setChecked(true);
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			mLocationClient.stop();
			finish();
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_backtofragment:
			mLocationClient.stop();
			this.finish();
			break;

		case R.id.jiaohuanfabu:
			mLocationClient.stop();
			if(!flag){
				try {
					SharedPreferences share1 = this.getSharedPreferences("login",
							Activity.MODE_WORLD_READABLE);

					String pid = share1.getString("id", "");
					if (!pid.equals("")) {
						
						jiaoHuan();
						this.finish();
						Toast.makeText(getApplicationContext(), "发布成功", 1).show();
					} else {
						Intent it5 = new Intent();
						it5.setClass(this, LoginActivity.class);
						startActivity(it5);
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				flag = true;
			}
			

			break;
		case R.id.chuantu:
			
			//隐藏虚拟键盘
			
			InputMethodManager imm = (InputMethodManager)getSystemService(JiaoHuanActivity.this.INPUT_METHOD_SERVICE); 
			
			imm.hideSoftInputFromWindow(jiaohuanbiaotitext.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(jianjietext.getWindowToken(), 0);

			
			getImage();
			break;
		case R.id.dingwei:
			InitLocation();
			mLocationClient.start();
			break;
		}
	}

	private void getImage() {

		spp = new SelectPicPopup(JiaoHuanActivity.this, itemsOnClick);
		spp.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);

	}

	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			spp.dismiss();
			switch (v.getId()) {
			case R.id.btn_take_photo:// 拍照
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					String saveDir = Environment.getExternalStorageDirectory()
							+ "/btl";
					File dir = new File(saveDir);
					if (!dir.exists()) {
						dir.mkdir();
					}
					filename = System.currentTimeMillis() + ".jpg";
					file = new File(saveDir, filename);
					file.delete();
					if (!file.exists()) {
						try {
							file.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
							return;
						}
					}
				}
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
				startActivityForResult(intent, 101);

				break;
			case R.id.btn_pick_photo:// 选取相册
				Intent intent1 = new Intent(Intent.ACTION_PICK, null);
				intent1.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				startActivityForResult(intent1, 200);

				break;
			default:
				break;
			}

		}

	};

	private void InitLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(tempMode);// 设置定位模式
		option.setCoorType(tempcoor);// 返回的定位结果是百度经纬度，默认值gcj02

		option.setScanSpan(1000 * 60 * 10);// 设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(checkGeoLocation.isChecked());
		mLocationClient.setLocOption(option);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		String path = null;
		switch (requestCode) {
		case 101:

			path = Environment.getExternalStorageDirectory() + "/btl/"
					+ filename;

			break;

		default:

			if (resultCode == Activity.RESULT_OK) {
				if (data != null && data.getData() != null) {
					// 根据返回的URI获取对应的SQLite信息
					Uri uri = data.getData();

					final String[] proj = { MediaStore.Images.Media.DATA };
					Cursor cursor = null;
					try {
						cursor = this.getContentResolver().query(uri, proj,
								null, null, null);
						int column_index = cursor
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						cursor.moveToFirst();
						path = cursor.getString(column_index);
					} finally {
						if (cursor != null) {
							cursor.close();
							cursor = null;
						}
					}
				}
			}

			break;
		}
		if (resultCode == Activity.RESULT_OK) {
			if (data != null && data.getData() != null) {
				// 根据返回的URI获取对应的SQLite信息
				Uri uri = data.getData();

				final String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = null;
				try {
					cursor = this.getContentResolver().query(uri, proj, null,
							null, null);
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					cursor.moveToFirst();
					path = cursor.getString(column_index);
				} finally {
					if (cursor != null) {
						cursor.close();
						cursor = null;
					}
				}
			}
		}
		if (path != null) {
			chuantu_id.setText(path);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 4;
			chuantu.setImageBitmap(BitmapFactory.decodeFile(path, options));
		} else {

			Toast.makeText(getApplicationContext(), "请从新选择图片", 1).show();
		}
	}

	private void jiaoHuan() throws FileNotFoundException {
		if (jiaohuanbiaotitext.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(), "帖子标题不能为空", 1).show();

		} else {
			AsyncHttpClient client = new AsyncHttpClient();
			RequestParams params = new RequestParams();
			params.add("jiaohuantitle", jiaohuanbiaotitext.getText().toString());
			params.add("jiaohuanjianjie", jianjietext.getText().toString());
			params.add("dingwei", LocationResult.getText().toString());
			params.put("jiaohuantupian", new File(chuantu_id.getText()
					.toString()));
			SharedPreferences share = getSharedPreferences("login",
					Activity.MODE_WORLD_READABLE);

			String id = share.getString("id", "");
			params.add("id", id);
			client.post(getResources().getString(R.string.url)
					+ "/CYGF/JiaoaHuanOp", params,
					new JsonHttpResponseHandler() {
						// 链接成功做出的反应
						@Override
						public void onSuccess(int statusCode, Header[] headers,
								JSONArray response) {
							JSONObject object1 = response.optJSONObject(1);
							JSONObject object = response.optJSONObject(0);
							String result = object.optString("msg");
							Toast.makeText(JiaoHuanActivity.this, result, 1)
									.show();
							super.onSuccess(statusCode, headers, response);

							Intent it = new Intent();
							it.setClass(JiaoHuanActivity.this,
									MainActivity.class);
							it.putExtra("type", 1);
							it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(it);
						}

						// 链接网络失败，做出的反应
						@Override
						public void onFailure(int statusCode, Header[] headers,
								Throwable throwable, JSONArray errorResponse) {
							super.onFailure(statusCode, headers, throwable,
									errorResponse);
						}
					});
		}

	}
}
